package com.winchain.provider.expiration.cmd;

import com.shell.framework.command.CommandContext;
import com.shell.framework.command.ICommand;
import com.winchain.provider.expiration.po.CbCredit;
import com.winchain.provider.expiration.rx.BillExpirationEvent;
import com.winchain.provider.expiration.service.CbCreditService;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class BillExpCreditMsgCmd implements ICommand<BillExpirationEvent> {
	@Autowired
	private CbCreditService cbCreditService;

	public boolean execute(CommandContext<BillExpirationEvent> context) throws Exception {
		String expDate = ((BillExpirationEvent) context.getSource()).getDate();
		String grpId = ((BillExpirationEvent) context.getSource()).getGrpId();
		List<CbCredit> credits = this.cbCreditService.getBillCredits(expDate, grpId, "1", null);
		Map<String, List<CbCredit>> cusCreditsMap = gatherCusCredits(credits);
		for (List<CbCredit> cusCredits : cusCreditsMap.values()) {
			this.cbCreditService.sendExpCreditMessage(expDate, cusCredits);
		}
		return false;
	}

	private Map<String, List<CbCredit>> gatherCusCredits(List<CbCredit> credits) {
		Map<String, List<CbCredit>> cusCreditsMap = new HashMap();
		for (CbCredit credit : credits) {
			String cusId = credit.getCusId();
			List<CbCredit> cusCredits = (List) cusCreditsMap.get(cusId);
			if (cusCredits == null) {
				cusCredits = new ArrayList();
				cusCreditsMap.put(cusId, cusCredits);
			}
			cusCredits.add(credit);
		}
		return cusCreditsMap;
	}
}
